class MessagesController < ApplicationController
before_filter :check_authorization
  layout "project"


  # GET /messages
  # GET /messages.xml
  def index
    #permission setting
    if @project.use_permission
    
     #user has permission

       filter_sql = filter_sql(@project,"msg")

       logger.error "-----------------------------------" 
       logger.error filter_sql
       logger.error "-----------------------------------" 

       if params[:category_id].to_i > 0
          if @cur_user.has_permission?("prj_" + @project.id.to_s + "_" + params[:category_id].to_s + "_msg_cat_view")
            @message_pages, @messages= paginate :messages, :per_page => 10, :conditions=>["project_id = ? and category_id = ? ",params[:project_id], params[:category_id]],:order => "id desc"
          else
            @message_pages, @messages= paginate :messages, :per_page => 10, :conditions=>["project_id = ? and (user_id = ? and category_id = ?) ",params[:project_id], @cur_user.id,params[:category_id]],:order => "id desc"
          end
       elsif params[:category_id] == "uncat"
          if @cur_user.has_permission?("prj_" + @project.id.to_s + "_unc_msg_cat_view")
            @message_pages, @messages= paginate :messages, :per_page => 10, :conditions=>["project_id = ? and (category_id is null or category_id = 0)",params[:project_id]],:order => "id desc"
          else
            @message_pages, @messages= paginate :messages, :per_page => 10, :conditions=>["project_id = ? and (user_id = ? and (category_id is null or category_id = 0))",params[:project_id], @cur_user.id],:order => "id desc"
          end
       else
          @message_pages, @messages= paginate :messages, :per_page => 10,:conditions=>["(project_id = ? and (#{filter_sql})) or (project_id = ? and user_id = #{@cur_user.id})",params[:project_id],params[:project_id]],:order => "id desc"
       end
   else
   # no use permissions 
     if params[:category_id].to_i > 0
       @message_pages, @messages= paginate :messages, :per_page => 10, :conditions=>["project_id = ? and category_id = ?",params[:project_id], params[:category_id]],:order => "id desc"
     elsif params[:category_id] == "uncat"
       @message_pages, @messages= paginate :messages, :per_page => 10,:conditions=>["project_id = ? and (category_id is null or category_id = 0) ",params[:project_id]],:order => "id desc"
     else
       @message_pages, @messages= paginate :messages, :per_page => 10,:conditions=>["project_id = ? ",params[:project_id]],:order => "id desc"
     end
   end
    respond_to do |format|
      format.html # index.rhtml
      format.xml  { render :xml => @messages.to_xml }
    end
  end

  # GET /messages/1
  # GET /messages/1.xml
  def show
    @message = Message.find(params[:id])

    respond_to do |format|
      format.html {
        #permission setting
        redirect_to nopermission_project_permission_path(@project) if @project.use_permission and (not @cur_user.has_permission?("prj_" + @message.project.id.to_s + "_" +  (@message.category_id.to_i > 0 ? @message.category_id.to_s : "unc") + "_msg_cat_view")) and @message.user_id != @cur_user.id 
	}
      format.xml  { render :xml => @message.to_xml }
    end
  end

  # GET /messages/new
  def new
    session[:up_files] = []
    @message = Message.new
    @cats = Project.find(params[:project_id]).msg_categories
    redirect_to nopermission_project_permission_path(@project) if @project.use_permission and ((@project.msg_categories.select{|c| @cur_user.has_permission?("prj_" + @project.id.to_s + "_#{c.id}_msg_cat_new")}.size == 0) and (not (@cur_user.has_permission?("prj_" + @project.id.to_s + "_unc_msg_cat_new"))))
  end

  # GET /messages/1;edit
  def edit
    @message = Message.find(params[:id])
    redirect_to nopermission_project_permission_path(@project) if @project.use_permission and (not @cur_user.has_permission?("prj_" + @message.project.id.to_s + "_" +  (@message.category_id.to_i > 0 ? @message.category_id.to_s : "unc") + "_msg_cat_edit")) and @message.user_id != @cur_user.id 
    @cats = Project.find(params[:project_id]).msg_categories
  end

  # POST /messages
  # POST /messages.xml
  def create
    @message = Message.new(params[:message])
    @message.project = Project.find(params[:project_id])
    @message.category = Category.find(params[:category_id]) if params[:category_id].to_i > 0 
    @message.user = @cur_user
    @message.body = CGI.unescapeHTML(params[:content])

    respond_to do |format|
      if @message.save

    unless params[:notify_id].nil?
      if params[:notify_id].size > 0
      #user_list = User.find(:all,:conditions => "id in (#{params[:notify_id].join(",")})").select{|a| (not a.email.nil?) and a.email.match("@")}.collect{|u| u.email}.join(",") 
      user_emails = User.find(:all,:conditions => "id in (#{params[:notify_id].join(",")})").select{|a| (not a.email.nil?) and a.email.match("@")}.collect{|u| u.email}
      #send user mail
      #Notifier.deliver_notify('new_message',user_list,@message,@cur_user.lang)
      user_emails.each do |email| 
        Notifier.deliver_notify('new_message',email,@message,@cur_user.lang)
      end
      end
    end
        #set files to this message
        file_rcs = Files.find(:all,:conditions=>["session_id = ?",CGI.unescape(session.session_id)]) 
	file_ids = params[:file_ids]
	file_category_ids = params[:file_category_ids]
        
	file_rcs.each_with_index do |f_rc,i|
	  if file_ids and file_ids.has_key?("#{i}")
	    f_rc.session_id = ""
	    f_rc.message_id = @message.id
	    f_rc.project_id = params[:project_id]
	    f_rc.user_id    = @cur_user.id
	    f_rc.category_id = file_category_ids["#{i}"].first.to_i
	    f_rc.save
	    logger.error f_rc.to_s
	  else
	    f_rc.destroy
	  end
	end
        flash[:notice] = @message.id
        format.html { 
	   redirect_to project_messages_path(@message.project)
	 }
        format.xml  { head :created, :location => project_message_path(@message) }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @message.errors.to_xml }
      end
    end
  end

  # PUT /messages/1
  # PUT /messages/1.xml
  def update
    @message = Message.find(params[:id])
    @message.category_id = params[:category_id] if params[:category_id]

    respond_to do |format|
      if @message.update_attributes(params[:message])
        flash[:notice] = 'Message was successfully updated.'
        format.html { 
	  if params[:category_id]
	   redirect_to project_msg_in_category_path(@message.project,params[:category_id]) 
	  else
	   redirect_to project_messages_path(@message.project) 
	  end
	}
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @message.errors.to_xml }
      end
    end
  end

  # DELETE /messages/1
  # DELETE /messages/1.xml
  def destroy
    @message = Message.find(params[:id])
    @message.destroy

    respond_to do |format|
      format.html { redirect_to project_messages_path}
      format.xml  { head :ok }
    end
  end
end
